package com.clas.liu.myapplication.view.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 轮播的viewpager
 * Created by liu on 2019/2/28.
 */

public class BannerViewPager extends ViewPager {


    private ScheduledExecutorService executorService;
    private boolean isRunning = false;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            setCurrentItem(getCurrentItem() + 1);
        }
    };

    public BannerViewPager(@NonNull Context context) {
        super(context);
    }

    public BannerViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void startBanner(){

        Log.i("test", "stopBanner: "+"滑动开始了！");
        //创建大小为1的固定线程池
        executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleWithFixedDelay(new BannerTask(),5,5, TimeUnit.SECONDS);
        isRunning = true;
    }

    public void stopBanner(){
        Log.i("test", "stopBanner: "+"滑动停止了！");
        if(executorService!=null){
            executorService.shutdown();
            executorService = null;
        }
        isRunning = false;
    }
    public boolean isRunning(){
        return isRunning;
    }
    private class BannerTask implements Runnable{

        @Override
        public void run() {
            handler.obtainMessage().sendToTarget();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                stopBanner();
                break;
            case MotionEvent.ACTION_UP:
                startBanner();
                break;
        }
        return super.onTouchEvent(ev);
    }


}
